import { CallbackFunction, EventName } from "./types";

// Interface for record change handler
// 记录变更处理接口
export interface ChangeRecord {
    (
        type: 'on' | 'once' | 'off' | 'emit' | 'all',
        eventName: EventName,
        callback: CallbackFunction | CallbackFunction[]
    ): any;
}

// Recorder configuration options
// 记录器配置选项
export interface RecordOptions{
    maxRecord?: number
    isRecord?: boolean
    changeRecord?: ChangeRecord
}

export type RecordType = 'on'|'once'|'off'|'emit'|'all'

// Record structure
// 记录结构
export interface Record {
    type: RecordType
    eventName?:string
    callback?: any,
    date: Date
}

// Create an event recorder
// 创建一个事件记录器
export function createRecorder(options:RecordOptions={}){
    const records: Array<Record> = []
    const maxRecord = options.maxRecord || 100
    const isRecord = options.isRecord === false ? false : true

    // Record operation logs
    // 记录操作记录
    function record(type: RecordType, eventName:EventName, callback: CallbackFunction | CallbackFunction[]){
       options.changeRecord?.(type, eventName, callback)
        if(!isRecord) return
        if(records.length >= maxRecord){
            records.splice(0,1)
        }
        records.push({
            type, 
            eventName: eventName ? eventName.toString(): null,
            callback,
            date: new Date()
        })
    }

    // Get records
    // 获取记录
    function getRecords(){
        // Return a new records array to prevent external modification
        // 返回一个新的records，防止外部修改
        return records.map(item => {
            return {
                ...item
            }
        })
    }

    // Clear records
    // 清空记录
    function clearRecords(){
        records.length = 0
    }

    return {
        records,
        record,
        maxRecord,
        getRecords,
        clearRecords
    }
}